<?php
/**
 * 该类主要完成对文件上传的处理
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/11/9
 * Time: 16:08
 */

namespace app\api\service;


use app\api\model\CardAudio;
use app\api\model\CardImg;
use app\api\model\CardVideo;
use app\api\model\Image;
use app\api\model\Poster;
use app\lib\exception\FileUplodeException;
use Qiniu\Auth;
use function Qiniu\base64_urlSafeEncode;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

class   FileUpload
{
    private $AccessKey;
    private $SecretKey;
    private $bucket;
    private $auth;
    function __construct()
    {
        $this->AccessKey=config('qiniu.AccessKey');
        $this->SecretKey=config('qiniu.SecretKey');
        $this->bucket=config('qiniu.bucket');
        vendor('qiniu.php-sdk.autoload');
        $this->auth = new Auth($this->AccessKey,$this->SecretKey);
    }

    /**
     * 颁发文件上传凭证
     * @param $uid
     * @return string
     */
    public function getUploadToken($uid,$type){
        $policy = array(
            'callbackUrl' => config('qiniu.notify_url'),
            'callbackBody' =>'{"fname":"$(fname)","fkey":"$(key)","bucket":"$(bucket)","type":"'.$type.'","uid":'.$uid .'}',
            'callbackBodyType' => 'application/json',
        );
        $upToken = $this->auth->uploadToken($this->bucket, null, 3600, $policy);
        return $upToken ;
    }

    /**
     * 上传回调函数
     * @return CardAudio|CardImg|CardVideo|Image|null
     * @throws FileUplodeException
     * @throws \think\exception\DbException
     */
    public function getCallbackInfo(){
        $url = config('qiniu.notify_url');
        $callbackBody = file_get_contents('php://input');
        $contentType = 'application/json';
        //回调的签名信息，可以验证该回调是否来自七牛
        $authorization = $_SERVER['HTTP_AUTHORIZATION'];
        $result =  $this->auth->verifyCallback($contentType,$authorization,$url,$callbackBody);
        if ($result) {
            $data = \Qiniu\json_decode($callbackBody);
            $img = '';
            if ($data->type == 'goods' || $data->type == 'poster'){//商品海报类图片
                $img = new Image();
            }elseif($data->type == 'user' || $data->type == 'introduce' ){//用户类图片
                $img = new CardImg();
            }elseif($data->type == 'audio'){//音频文件
                $img = new CardAudio();
            }elseif($data->type == 'video'){//视频文件
                $img = new CardVideo();
            }
            $info = $img::createImg($data);
            return $info;
        } else {
            throw new FileUplodeException();
        }
    }

    /**
     * 上传数据通知回调
     * @return mixed
     * @throws FileUplodeException
     */
    public function getPersistentCallbackInfo(){
        $callbackBody = file_get_contents('php://input');
        if (!empty($callbackBody)) {
            $data = \Qiniu\json_decode($callbackBody);
            $result =  CardAudio::updateImg($data);
            if (!empty($result)){
                $this->deleteQiniuFile($data->inputKey);//删除转码前的文件
            }
            return $result;
        } else {
            throw new FileUplodeException();
        }
    }

    /**
     * 文件服务器直传,文件类型处理
     * @param $key
     * @param $path
     * @return mixed
     * @throws \Exception
     */
    public function uploadFile($key,$path,$uid,$type = ''){
        $policy =null;
        if ($type =='audio' && !empty($type)){
            $savekey = base64_urlSafeEncode($this->bucket.':'.rtrim($key,'.amr').'.mp3');
            $policy = array(
                'callbackUrl' => config('qiniu.notify_url'),
                'callbackBody' =>'{"fname":"$(fname)","fkey":"$(key)","bucket":"$(bucket)","type":"'.$type.'","uid":'.$uid .'}',
                'callbackBodyType' => 'application/json',
                'persistentOps' => 'avthumb/mp3/ab/320k/ar/44100/acodec/libmp3lame|saveas/'.$savekey,//7牛云转码,令存为
                'persistentPipeline' => 'handleAudio',//7牛云多媒体处理队列
                'persistentNotifyUrl'=>config('qiniu.persistent_notify_url')//7牛云音视频处理回调url
            );
        }
        $token = $this->auth->uploadToken($this->bucket, null, 3600, $policy);
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token,$key,$path);
        if ($err !== null) {
            return $err;
        } else {
            return $ret;
        }
    }

    /**
     * s删除图片
     * @param $uid
     * @param $img_id
     * @param $type
     * @return mixed|string
     * @throws FileUplodeException
     * @throws \think\exception\DbException
     */
    public function deleteFile($uid,$img_id,$type){
        $img = '';
        if ($type == 'goods'){
            $img = new Image();
        }elseif($type == 'user' || $type =='introduce'){
            $img = new CardImg();
        }elseif ($type == 'audio'){
            $img = new CardAudio();
        }elseif ($type == 'video'){
            $img = new CardVideo();
        }
        $img =  $img->getImg($img_id);
        $err = '';
        if (!empty($img)){
            if ($img->from == 2){//远程图片删除
                $err = $this->deleteQiniuFile($img->key);//删除7牛文件
                if (!empty($err)){
                    throw new FileUplodeException();
                }
                $img->deleteImg($img_id);//删除文件
            }elseif ($img->from == 1){//本地图片删除
                $err = 'ok';
            }
        }
        return $err;
    }

    /**
     * 删除7牛文件
     * @param $img
     * @return mixed
     */
    public function deleteQiniuFile($key)
    {
        $config = new \Qiniu\Config();
        $bucketManager = new \Qiniu\Storage\BucketManager($this->auth, $config);
        $err = $bucketManager->delete($this->bucket, $key);
        return $err;
    }

    /**
     * 复制7牛文件
     * @param $srcBucket 源空间
     * @param $destBucket 目标空间
     * @param $srcKey 源ke'y
     * @param $destKey 目标key
     * @return mixed
     */
    public function copyFile($srcBucket,$destBucket,$srcKey,$destKey){
        $config = new \Qiniu\Config();
        $bucketManager = new \Qiniu\Storage\BucketManager($this->auth, $config);
        $err = $bucketManager->copy($srcBucket, $srcKey, $destBucket, $destKey, true);
       return $err;
    }

    /**
     * 批量复制
     * @param $srcBucket
     * @param $destBucket
     * @param $srcKey
     * @return array
     */
    public function batchCopyFile($srcBucket,$destBucket,$srcKey){
        $config = new \Qiniu\Config();
        $bucketManager = new \Qiniu\Storage\BucketManager($this->auth, $config);
        $ops = $bucketManager->buildBatchCopy($srcBucket, $srcKey, $destBucket, true);
        list($ret, $err) = $bucketManager->batch($ops);
        return $ret;
    }



}